import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class UnzipSubtitles {

	private String zipFile;
	private File outputDir;
	private File zipOutputDir;
	private Map<String, String> nameTable;

	public UnzipSubtitles(String aZipFilePath) {
		zipFile = aZipFilePath;
	}

	public static void main(String[] args) throws Throwable {

		new UnzipSubtitles(args[0]).run();
	}

	private void run() throws Throwable {
		UnzipFile unzipFile = new UnzipFile();
		unzipFile.getZipFiles(zipFile);
		zipOutputDir = unzipFile.getOutputDir();
		outputDir = new File(zipFile).getParentFile();
		createNameTable();
		copySubtitles();
	}

	private void createNameTable() {
		nameTable = new HashMap<String, String>();
		File[] files = outputDir.listFiles();

		for (int i = 0; i < files.length; i++) {
			String currentFilename = files[i].getName();
			String episode = EpisodeGetter.getEpisode(currentFilename);
			if (episode != null) {
				nameTable.put(episode, currentFilename);
			} else {
				System.out
						.println("NO MATCHING EPISODE for " + currentFilename);
			}
		}
	}

	private void copySubtitles() throws Throwable {
		List<File> subtitlesFiles = new ArrayList<File>();
		subtitlesFiles.add(zipOutputDir);
		File otherSubtitlesDir = new File(outputDir, "others subtitles");
		otherSubtitlesDir.mkdirs();

		while (!subtitlesFiles.isEmpty()) {
			File current = subtitlesFiles.get(subtitlesFiles.size() - 1);
			subtitlesFiles.remove(subtitlesFiles.size() - 1);

			if (current.isDirectory()) {
				File[] sons = current.listFiles();

				for (int i = 0; i < sons.length; i++) {
					subtitlesFiles.add(sons[i]);
				}
			} else {
				if (current.getName().endsWith(".srt")) {
					String episode = EpisodeGetter
							.getEpisode(current.getName());
					if (episode != null) {
						String aviName = nameTable.get(episode);
						String newName = aviName.substring(0,
								aviName.length() - 4) + ".srt";
						System.out.println(newName);
						File outputFile = new File(outputDir, newName);
						while (outputFile.exists()) {
							outputFile = new File(otherSubtitlesDir, outputFile
									.getName().replace(".srt", "_.srt"));
						}
						FileCopy.copy(current, outputFile);
					} else {
						System.out.println("NO MATCHING EPISODE for "
								+ current.getName());
					}
				}
			}
		}
	}
}
